package com.lxq.LeetCode.myAtoi;

public class Solution {
    public static void main(String[] args) {
        System.out.println(myAtoi("4193"));
    }

    public static int myAtoi(String s) {
        if (s.length() == 0) {
            return 0;
        }
        long res = 0;
        int p = 0;
        int symbol = 1;
        while (p < s.length() && s.charAt(p) == ' ') {
            p++;
        }
        if (p < s.length() && s.charAt(p) == '-') {
            symbol = -1;
            p++;
        } else if (p < s.length() && s.charAt(p) == '+') {
            p++;
        }
        while (p < s.length()) {
            int temp = s.charAt(p) - '0';
            if ((temp <= 9 && temp >= 0)) {
                res = res * 10 + temp;
                if (res * symbol < Integer.MIN_VALUE) {
                    res = Integer.MIN_VALUE;
                    break;
                }
                if (res * symbol > Integer.MAX_VALUE) {
                    res = Integer.MAX_VALUE;
                    break;
                }
                p++;
            } else {
                break;
            }

        }

        return (int) res * symbol;
    }
}
